<?php
namespace app\common\model;

trait CUBaseTrait {
	// 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $statusKey  = 'status';
    protected $examineKey = 'examine';

    protected $privacyFields = ['status', 'updatetime'];
    
    protected $isShowList = false;
    protected $statusEnum = 'Status';
    protected $examineEnum = 'Examine';

    protected function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
 
    protected function getUpdatetimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    //只查询显示的数据
    public function show_list() {
        if($this->isShowList) {
            return $this;
        }
        $this->isShowList = true;
        $statusKey = $this->statusKey;
        if($statusKey) {
            if($this->aliasName) {
                $statusKey = $this->aliasName . '.' . $statusKey;
            }
            return $this->where($statusKey, loadEnum($this->statusEnum)->showStatus());
        } else {
            return $this;
        }
    }

    //返回状态文本信息
    public function getStatusTextAttr() {
        $options = loadEnum($this->statusEnum)->get_options();
        try {
            return $options[$this->getData($this->statusKey)];
        } catch(\InvalidArgumentException $e) {
            return null;
        }
    }

    //返回是否显示
    public function getIsShowAttr() {
        try {
            return loadEnum($this->statusEnum)->isShow($this->getData($this->statusKey));
        } catch(\InvalidArgumentException $e) {
            return null;
        }
    }

    //返回审核状态文本信息
    public function getExamineTextAttr() {
        try {
            $options = loadEnum($this->examineEnum)->get_options();
            return $options[$this->getData($this->examineKey)];
        } catch(\InvalidArgumentException $e) {
            return null;
        }
    }

    //返回是否审核
    public function getIsExamineAttr() {
        try {
            return loadEnum($this->examineEnum)->isComplete($this->getData($this->examineKey));
        } catch(\InvalidArgumentException $e) {
            return null;
        }
    }

    //显示内容
    public function show($id = null) {
        if(!$id) {
            $id = $this->getData($this->getPk());
        }
        $this->where([$this->getPk() => $id])->update([$this->statusKey => loadEnum('Status')->showStatus(), $this->updateTime => time()]);
    }

    //隐藏内容
    public function hide($id = null) {
        if(!$id) {
            $id = $this->getData($this->getPk());
        }
        $this->where([$this->getPk() => $id])->update([$this->statusKey => loadEnum('Status')->hideStatus(), $this->updateTime => time()]);
    }

    //返回表里的可修改字段
    public function getTableDataFields() {
        $fields = $this->getTableFields();
        return array_diff($fields, [$this->getPk(), $this->createTime, $this->updateTime]);
    }
}